package com.itany.cloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.itany.cloud.util.ResponseResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 石小俊
 */
@RestController
@RequestMapping
public class HelloController {

    // value:指定当前需要处理的资源是谁,其值即为当前资源名,不能带有/。如果没有指定资源名,则直接使用空字符串
    // blockHandler:指定哪一个方法用来处理超出阈值的场景,其值对应的是当前类中的某一个方法
    // 该方法需要满足几个条件
    // 1.必须在当前类中
    // 2.方法的返回值类型与当前需要处理的请求方法的返回值类型一致
    // 3.该方法的修饰符必须是public
    // 4.方法的参数必须与原方法参数一致,且多一个BlockException
//    @SentinelResource(value = "f1", blockHandler = "handlerException")
    @RequestMapping("/f1")
    public ResponseResult f1() {
        return ResponseResult.success();
    }

    public ResponseResult handlerException(BlockException e) {
        return ResponseResult.fail("Sentinel异常,异常为:" + e);
    }


    // blockHandlerClass:指定哪一个类是用于处理Sentinel异常的
    // blockHandler:当指定了blockHandlerClass之后,其值必须是对应class中的方法
//    @SentinelResource(value = "f2",blockHandlerClass = GlobalSentinelException.class,blockHandler = "handlerException")
    @RequestMapping("/f2")
    public ResponseResult f2() {
        return ResponseResult.success();
    }

    @RequestMapping("/f3")
    public ResponseResult f3(){
        System.out.println("当前时间:"+System.currentTimeMillis());
        return ResponseResult.success();
    }

    @RequestMapping("/f4/{id}")
    public ResponseResult f4(@PathVariable Integer id){
        if(id == 1){
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        if(id == 2){
            int i = 1 / 0;
        }
        return ResponseResult.success();
    }

    @SentinelResource(value = "f5",blockHandler = "handlerException5")
    @RequestMapping("/f5")
    public ResponseResult f5(String s1,String s2){
        return ResponseResult.success("f5执行成功,第一个参数为:"+s1+",第二个参数为:"+s2);
    }

    public ResponseResult handlerException5(String s1,String s2,BlockException e){
        return ResponseResult.fail("Sentinel热点参数异常,异常为:"+e);
    }

    @RequestMapping("/f6")
    public ResponseResult f6(){
        return ResponseResult.success("授权规则测试通过");
    }
}
